<template>
  <div>
    <!-- 搜索区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="分类">
        <el-select v-model="searchModel.categoryId" placeholder="请选择分类" clearable>
          <el-option
            v-for="category in categories"
            :key="category.categoryId"
            :label="category.name"
            :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题型">
        <el-select v-model="searchModel.questionType" placeholder="请选择题型" clearable>
          <el-option label="单选题" value="single" />
          <el-option label="多选题" value="multiple" />
          <el-option label="判断题" value="judge" />
          <el-option label="简答题" value="essay" />
        </el-select>
      </el-form-item>
      <el-form-item label="难度">
        <el-select v-model="searchModel.difficultyLevel" placeholder="请选择难度" clearable>
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目标题">
        <el-input v-model="searchModel.title" placeholder="请输入题目标题" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="updateOradd(null)">新增</el-button>
        <el-button type="danger" :disabled="ids.length == 0" @click="delDataByIds">批量删除</el-button>
        <el-button type="info" @click="exportData">导出题目</el-button>
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="importSuccess"
          :on-error="importError"
          :show-file-list="false"
          accept=".xlsx,.xls"
          style="display: inline-block; margin-left: 10px;"
        >
          <el-button type="warning">批量导入</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="题目标题" width="200" />
      <el-table-column prop="content" label="题目内容" show-overflow-tooltip />
      <el-table-column prop="questionType" label="题型" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getQuestionTypeTag(scope.row.questionType)"
            size="small"
          >
            {{ getQuestionTypeText(scope.row.questionType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="difficultyLevel" label="难度级别" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getDifficultyType(scope.row.difficultyLevel)"
            size="small"
          >
            {{ getDifficultyText(scope.row.difficultyLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="score" label="分值" width="80" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
          <el-button size="mini" @click="updateOradd(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="delData(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      :current-page="searchModel.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="80%">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="题目标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入题目标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="questionType">
              <el-select v-model="form.questionType" placeholder="请选择题目类型" @change="onQuestionTypeChange">
                <el-option label="单选题" value="single" />
                <el-option label="多选题" value="multiple" />
                <el-option label="判断题" value="judge" />
                <el-option label="简答题" value="essay" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入题目内容"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类">
                <el-option
                  v-for="category in categories"
                  :key="category.categoryId"
                  :label="category.name"
                  :value="category.categoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度级别" prop="difficultyLevel">
              <el-select v-model="form.difficultyLevel" placeholder="请选择难度级别">
                <el-option label="简单" value="简单" />
                <el-option label="中等" value="中等" />
                <el-option label="困难" value="困难" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分值" prop="score">
              <el-input-number
                v-model="form.score"
                :min="1"
                :max="100"
                placeholder="请输入分值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

                <!-- 选择题选项 -->
        <div v-if="form.questionType === 'single' || form.questionType === 'multiple'">
          <el-form-item label="题目选项">
            <div v-for="(option, index) in form.options" :key="index" style="margin-bottom: 10px;">
              <el-row :gutter="10" type="flex" align="middle">
                <el-col :span="2">
                  <el-tag type="primary">{{ option.key }}</el-tag>
                </el-col>
                <el-col :span="18">
                  <el-input
                    v-model="option.content"
                    :placeholder="`请输入选项${option.key}内容`"
                  />
                </el-col>
                <el-col :span="4" style="text-align: right;">
                  <el-button
                    v-if="form.options.length > 2"
                    type="danger"
                    size="mini"
                    @click="removeOption(index)"
                    style="margin-left: 10px;"
                  >
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button
              v-if="form.options.length < 6"
              type="primary"
              size="mini"
              @click="addOption"
            >
              添加选项
            </el-button>
          </el-form-item>
        </div>

        <!-- 正确答案 -->
        <el-form-item label="正确答案" prop="correctAnswer">
          <!-- 单选题 -->
          <el-radio-group v-if="form.questionType === 'single'" v-model="form.correctAnswer">
            <el-radio
              v-for="(option, index) in form.options"
              :key="index"
              :label="option.key"
            >
              选项{{ option.key }}
            </el-radio>
          </el-radio-group>

          <!-- 多选题 -->
          <el-checkbox-group v-else-if="form.questionType === 'multiple'" v-model="form.correctAnswerArray">
            <el-checkbox
              v-for="(option, index) in form.options"
              :key="index"
              :label="option.key"
            >
              选项{{ option.key }}
            </el-checkbox>
          </el-checkbox-group>

          <!-- 判断题 -->
          <el-radio-group v-else-if="form.questionType === 'judge'" v-model="form.correctAnswer">
            <el-radio label="正确">正确</el-radio>
            <el-radio label="错误">错误</el-radio>
          </el-radio-group>

          <!-- 简答题 -->
          <el-input
            v-else-if="form.questionType === 'essay'"
            v-model="form.correctAnswer"
            type="textarea"
            :rows="3"
            placeholder="请输入参考答案"
          />
        </el-form-item>

        <el-form-item label="题目解析">
          <el-input
            v-model="form.analysis"
            type="textarea"
            :rows="3"
            placeholder="请输入题目解析（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAndSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import questionManger from '@/api/questionManger'
import categoryManger from '@/api/categoryManger'

export default {
  data() {
    return {
      searchModel: {
        categoryId: null,
        questionType: '',
        difficultyLevel: '',
        title: '',
        pageSize: 10,
        currentPage: 1
      },
      total: 0,
      tableData: [],
      form: {},
      dialogFormVisible: false,
      title: '',
      categories: [],
      rules: {
        title: [
          { required: true, message: '请输入题目标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        difficultyLevel: [
          { required: true, message: '请选择难度级别', trigger: 'change' }
        ],
        score: [
          { required: true, message: '请输入分值', trigger: 'blur' },
          { type: 'number', min: 1, max: 100, message: '分值必须在1-100之间', trigger: 'blur' }
        ],
        correctAnswer: [
          { required: true, message: '请设置正确答案', trigger: 'blur' }
        ]
      },
      ids: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/question/importData',
      uploadHeaders: {}
    }
  },
  mounted() {
    this.getTableData()
    this.getAllCategories()
    // 设置上传请求头
    this.uploadHeaders = {
      'Authorization': 'Bearer ' + this.$store.getters.token
    }
  },
  methods: {
    // 获取题目数据
    getTableData() {
      questionManger.getTableDataApi(this.searchModel).then(res => {
        this.tableData = res.data.questions
        this.total = res.data.total
      })
    },

    // 获取所有分类
    getAllCategories() {
      categoryManger.getAllCategoriesApi().then(res => {
        this.categories = res.data
      })
    },

    // 每页显示条数变化
    handleSizeChange(size) {
      this.searchModel.pageSize = size
      this.getTableData()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.searchModel.currentPage = page
      this.getTableData()
    },

    // 重置搜索
    reset() {
      this.searchModel.categoryId = null
      this.searchModel.questionType = ''
      this.searchModel.difficultyLevel = ''
      this.searchModel.title = ''
      this.getTableData()
    },

    // 新增/编辑对话框
    updateOradd(row) {
      if (row == null) {
        this.title = '新增题目'
        this.form = {
          title: '',
          content: '',
          questionType: 'single',
          categoryId: null,
          difficultyLevel: '',
          score: 5,
          correctAnswer: '',
          correctAnswerArray: [],
          analysis: '',
          options: [
            { key: 'A', content: '', isCorrect: false },
            { key: 'B', content: '', isCorrect: false }
          ]
        }
      } else {
        this.title = '编辑题目'
        this.form = {
          ...row,
          correctAnswerArray: row.correctAnswer ? row.correctAnswer.split(',') : [],
          options: row.options || [
            { key: 'A', content: '', isCorrect: false },
            { key: 'B', content: '', isCorrect: false }
          ]
        }
      }
      this.dialogFormVisible = true
    },

    // 题目类型变化
    onQuestionTypeChange(type) {
      if (type === 'single' || type === 'multiple') {
        // 选择题初始化选项
        if (!this.form.options || this.form.options.length < 2) {
          this.form.options = [
            { key: 'A', content: '', isCorrect: false },
            { key: 'B', content: '', isCorrect: false }
          ]
        }
      } else {
        // 非选择题清空选项
        this.form.options = []
      }
    },

    // 添加选项
    addOption() {
      if (this.form.options.length < 6) {
        const optionKeys = ['A', 'B', 'C', 'D', 'E', 'F']
        this.form.options.push({
          key: optionKeys[this.form.options.length],
          content: '',
          isCorrect: false
        })
      }
    },

    // 删除选项
    removeOption(index) {
      if (this.form.options.length > 2) {
        this.form.options.splice(index, 1)
        // 重置正确答案
        this.form.correctAnswer = ''
        this.form.correctAnswerArray = []
      }
    },

    // 保存
    updateAndSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 处理多选题答案
          if (this.form.questionType === 'multiple' && this.form.correctAnswerArray.length > 0) {
            this.form.correctAnswer = this.form.correctAnswerArray.join(',')
          }

          // 验证选择题选项
          if ((this.form.questionType === 'single' || this.form.questionType === 'multiple')) {
            const hasEmptyOption = this.form.options.some(option => !option.content.trim())
            if (hasEmptyOption) {
              this.$message.error('请填写完整的选项内容')
              return false
            }
          }

          questionManger.updateAndSaveApi(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.getTableData()
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.$message.error('请填写完整信息')
          return false
        }
      })
    },

    // 删除
    delData(row) {
      this.$confirm(`此操作将永久删除题目 ${row.title}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        questionManger.delDataApi(row.questionId).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.questionId)
    },

    // 批量删除
    delDataByIds() {
      this.$confirm('此操作将永久删除选中题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        questionManger.delDataByIdsApi(this.ids).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 获取题型标签类型
    getQuestionTypeTag(type) {
      const typeMap = {
        'single': 'primary',
        'multiple': 'success',
        'judge': 'warning',
        'essay': 'info'
      }
      return typeMap[type] || 'info'
    },

    // 获取题型文本
    getQuestionTypeText(type) {
      const textMap = {
        'single': '单选题',
        'multiple': '多选题',
        'judge': '判断题',
        'essay': '简答题'
      }
      return textMap[type] || type
    },

    // 获取难度类型
    getDifficultyType(level) {
      const typeMap = {
        '简单': 'success',
        '中等': 'warning',
        '困难': 'danger'
      }
      return typeMap[level] || 'info'
    },

    // 获取难度文本
    getDifficultyText(level) {
      return level || '未设置'
    },

    // 查看题目详情
    viewDetail(row) {
      this.$alert(`
        <div style="text-align: left;">
          <p><strong>题目标题：</strong>${row.title}</p>
          <p><strong>题目内容：</strong>${row.content}</p>
          <p><strong>题目类型：</strong>${this.getQuestionTypeText(row.questionType)}</p>
          <p><strong>难度级别：</strong>${row.difficultyLevel}</p>
          <p><strong>分值：</strong>${row.score || 5}分</p>
          <p><strong>正确答案：</strong>${row.correctAnswer || '未设置'}</p>
          <p><strong>题目解析：</strong>${row.analysis || '无解析'}</p>
        </div>
      `, '题目详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      })
    },

    // 导出题目
    exportData() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      questionManger.exportDataApi()
        .then(response => {
          console.log('导出响应:', response)

          // 检查响应状态
          if (response.status !== 200) {
            throw new Error('导出请求失败，状态码：' + response.status)
          }

          // 检查响应数据
          if (!response.data) {
            throw new Error('导出数据为空')
          }

          // 创建blob对象
          const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })

          // 检查blob大小
          if (blob.size === 0) {
            throw new Error('导出文件为空')
          }

          // 创建下载链接
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = '题目数据.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)

          this.$message.success('导出成功！')
        })
        .catch(error => {
          console.error('导出失败详情:', error)
          let errorMessage = '导出失败！'
          if (error.response) {
            errorMessage += ' 状态码：' + error.response.status
          }
          if (error.message) {
            errorMessage += ' 错误信息：' + error.message
          }
          this.$message.error(errorMessage)
        })
        .finally(() => {
          loading.close()
        })
    },

    // 导入成功回调
    importSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('导入成功！')
        this.getTableData()
      } else {
        this.$message.error(response.message || '导入失败！')
      }
    },

    // 导入失败回调
    importError(error, file, fileList) {
      console.error('导入失败:', error)
      this.$message.error('导入失败！')
    }
  }
}
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
</style>
